package chances.wechat.utils.taglib;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import chances.epg.commons.utils.PathUtils;
import chances.epg.commons.utils.SpringWebUtils;
import chances.wechat.config.WeChatMvcConfig;

public class WechatUrlTag extends TagSupport {

	private static final long serialVersionUID = -4217819593098337323L;

	private String var;
	private String action;
	private String from;
	private String host;
	private String path;

	private static final String WX_ACTION_LOGIN = "login";

	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

		WeChatMvcConfig wechatConfig = SpringWebUtils.findBean(pageContext, WeChatMvcConfig.class);
		host = wechatConfig.getEpgHost();
		//wgHost = wechatConfig.getWgHost();

		String result = "";
		if (action.equals(WX_ACTION_LOGIN)) {
			result = this.getWxLoginPath(request);
		} else {
			result = this.getPath(request);
		}
		pageContext.setAttribute(this.var, result);
		return super.doStartTag();
	}

	private String getPath(HttpServletRequest request) {
		//return PathUtils.join(this.wgHost, this.path);
		return PathUtils.join(request.getContextPath(),this.path);
	}

	private String getWxLoginPath(HttpServletRequest request) {
		String url = PathUtils.join(host,"/login/user.wx?from=");
		return url + from;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	@Override
	public void release() {
		this.var = "";
		this.action = "";
		this.path = "";
		super.release();
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}
